<?php
/**
 * 图片上传类
 * @文件名称: Upload.php
 * @author: jawei
 * @Email: gaozhiwei@etcp.cn
 * @Date: 2017-06-06
 * @Copyright: 2017 悦畅科技有限公司. All rights reserved.
 * 注意：本内容仅限于悦畅科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
namespace app\lib;
use app\base\BaseService;
use Yii;
use app\lib\UpYun;
use app\lib\Trace;
use yii\base\ErrorException;
use yii\base\Exception;

class Upload {
    
    public static $upyun = null;
    /**
     * 上传到又拍云
     *
     * @param  $file    文件的绝对地址
     * @param   $is_thumb   是否生成缩略图
     * @return string  返回url
     **/
    public static function toYun($file, $is_thumb = false, $isPay = true, $path = '') {
        //static $upyun ;
        if (self::$upyun === null)  {
            require_once(Yii::$app->basePath . '/lib/UpYun.php');
            //require_once('../../common/lib/UpYun.php');
            $app = Yii::$app->params['yun']['space'];
            $user  = Yii::$app->params['yun']['user'];
            $pwd  = Yii::$app->params['yun']['pwd'];
            $upyun = new UpYun($app, $user, $pwd);
        }
        $opts = array(
            UpYun::CONTENT_MD5 => md5(file_get_contents($file))
        );
        $res = ['code' => 0];
        $fh = fopen($file , 'rb');
        if ($isPay) {
            $filePath = '/images/' . basename($file);
        } else {
            $filePath = $path . basename($file) ;
        }
        //$filePath = '/' . date("Y-m-d") .'/' . basename($file);
        $rsp = $upyun->writeFile($filePath, $fh, True, $opts);   // 上传图片，自动创建目录
        fclose($fh);
        if (count($rsp)) {
            $res['file'] = $filePath;
            //$res['file'] = basename($file);
        } else {
            $res['code'] = 500;
        }
        if ($is_thumb == false) {
            return $res;
        }
        $opts = array(
            UpYun::X_GMKERL_TYPE    => 'square', // 缩略图类型
            UpYun::X_GMKERL_VALUE   => 150, // 缩略图大小
            UpYun::X_GMKERL_QUALITY => 95, // 缩略图压缩质量
            UpYun::X_GMKERL_UNSHARP => True // 是否进行锐化处理
        );
        $filePath = '/images/t_' . basename($file); 
        $fh = fopen($file , 'rb');
        $rsp = $upyun->writeFile($filePath, $fh, True, $opts);   // 上传图片，自动创建目录
        fclose($fh);
        if (count($rsp)) {
            $res['thumb_file'] = $filePath;
            //$res['thumb_file'] = basename($filePath);
        }         
        return $res;
    }
    /**
     * 生成图片
     * @param   string  $fileName   文件的名字,input file的name
     * @param   boolen  $isToyun    是否要上传到又拍云
     * @param   int     $uid        企业的id
     * @return url
     **/
    public static function createFile($uid, $isToyun = false, $fileName = 'file') {
        //添加 excel类型
        $types = array(  
            'image/jpg',  
            'image/jpeg',  
            'image/png',  
            'image/pjpeg',  
            'image/gif',  
            'image/bmp',  
            'image/x-png' ,
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-excel',
			'application/octet-stream',
        );  

        if (!Yii::$app->request->isPost) {
            return ['code' => 403, 'msg' => '提交姿势不对'] ;
        }

		if (!isset($_FILES[$fileName])) {
            return ['code' => 403, 'msg' => '上传name不对'] ;
		}
        //上传文件
        if (!is_uploaded_file($_FILES[$fileName]['tmp_name'])) {
            return ['code' => 404, 'msg' => '文件找不到'] ;
        }

        $file = $_FILES[$fileName];
        //根据用户反馈，去除了这个,有可能出问题
        if (!in_array($file['type'], $types)) {
			Trace::addLog('upload_file', 'error', ['type' => $file['type'], 'file' => $file]);
            //return ['errno' => 404, 'msg' => '文件类型不支持'] ;
        }
        if (Yii::$app->params['upload']['max'] < $file['size']) {
            return ['code' => 403, 'msg' => '超出文件大小限制'] ;
        }
        if ($file['error'] > 0) {
            return ['code' => 403, 'msg' => 'error : ' . $file['error']] ;
        }
        $info = pathinfo($file["name"]); 
		if (!is_dir(Yii::$app->params['upload']['path'])) {
			//如果没有目录的话，创建目录
			mkdir(Yii::$app->params['upload']['path']);	
		}
        $newFile = Yii::$app->params['upload']['path'] . md5($uid . time() . rand(0,1000)) . '.'. $info['extension'];
        if (!move_uploaded_file($file['tmp_name'], $newFile)) {
            return ['code' => 500, 'msg' => '移动文件出错'] ;
        }
        @chmod($newFile, 0744);
        if ($isToyun) {
			$rs = self::toYun($newFile, true);
			return  $rs;
        } else {
            return ['code' => 200, 'file' => $newFile, 'msg' => 'ok'];
        }
    }

    /**
     *  生成excel对象
     *
     **/
    public static function getExcelObj($file)
    {
        include (Yii::$app->basePath . '/lib/phpexcel/PHPExcel.php');
        include(Yii::$app->basePath . "/lib/phpexcel/PHPExcel/IOFactory.php");
        //include("../../common/phpexcel/PHPExcel.php");
        //include("../../common/phpexcel/PHPExcel/IOFactory.php");
        //$reader = \PHPExcel_IOFactory::createReader('Excel2007'); //设置以Excel5格式(Excel97-2003工作簿)
        $PHPExcel = false;
        try {
            $reader = \PHPExcel_IOFactory::createReader('Excel2007'); //设置以Excel5格式(Excel97-2003工作簿)
            $PHPExcel = $reader->load($file); // 载入excel文件
        } catch (\Exception $e) {
            Trace::addLog('excel_format_exception_2007', 'warning', 
                [
                    'file' => $file, 
                    'msg' => $e->getMessage(),
                    'file' => $file,
                ]
            );
            //throw new Exception('excel 无法解析，请导出为Excel97-2003', 500);
        }
        if ($PHPExcel == false) {
            try {
                $reader = \PHPExcel_IOFactory::createReader('Excel5'); //设置以Excel5格式(Excel97-2003工作簿)
                $PHPExcel = $reader->load($file); // 载入excel文件
            } catch (\Exception $e) {
                Trace::addLog('excel_format_exception_excel5', 'warning', 
                    [
                        'file' => $file, 
                        'msg' => $e->getMessage(),
                        'file' => $file,
                    ]
                );
                throw new Exception('excel 无法解析，请导出为Excel97-2003', 500);
            }
        }
		if ($PHPExcel == false) {
            throw new Exception('excel 无法解析，请导出为Excel97-2003', 500);
		}
        return $PHPExcel;
    }
    /**
     * @param $files $_FILES['file']文件对象
     * @param $path 保存文件到本地路径地址
     * @param int $size 默认为2M  文件大小限制
     */
    public static function saveFile($files, $size=2, $filesType=[]) {
        try{
            $mSize = $size * 1024*1000;
            $code = 0;
            $msg = 'success';
            $array = explode('.',$files['name']);
            $houzhui = $array[count($array)-1];
            if(in_array($files["type"], $filesType)){
                if($files["size"] >= $mSize) {
                    $code = 500;
                    $msg = '文件大小不能超过'. $size ."M";
                    return BaseService::returnErrData([], $code, $msg);
                }
                if ($files["error"] > 0) {
                    $code = $files["error"];
                    $msg = '上传失败';
                    return BaseService::returnErrData([], $code, $msg);
                }
                $newFiilPath = "./uploads/".date('Ymd').'/'.date('m').'/'.date('d').'/';
                try{
                    if(!file_exists($newFiilPath)){
                        mkdir($newFiilPath, 0777, true);
                    }
                }catch (\Exception $e) {
                    system("mkdir -p " . $newFiilPath);
                }
                $file = $newFiilPath . Common::getRandChar(15).time().".".$houzhui;
                if(!move_uploaded_file($files['tmp_name'], $file)){
                    $code = 500;
                    $msg = '上传失败请联系网站管理员';
                    return BaseService::returnErrData([], $code, $msg);
                }
                return BaseService::returnOkData(['src' => substr($file,1),'title'=>''], $code, $msg);
            }
            return BaseService::returnErrData([], 500, '当前格式不支持上传');
        }  catch (\Exception $e) {
            $log = [
                'msg'    => $e->getMessage(),
                'data' => $e,
            ];
            Trace::addLog('resetRedisLogin_exception', 'error', $log);
            return BaseService::returnErrData([], 500, '服务器异常');
        }
    }
}
